package com.sgb.kjwl.viewmodel.supplier3;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.TextUtils;
import android.widget.Toast;

import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.EnquiryImAlternateEntity;
import com.sgb.kjwl.model.entity.CompanyDetailsEntity;
import com.sgb.kjwl.model.entity.ConcreteDetailEntity;
import com.sgb.kjwl.model.entity.GoodsSkuDetailEntity;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.ShoppingCarRequest;
import com.sgb.kjwl.model.entity.manage.WebsiteInfoEntity;
import com.sgb.kjwl.model.entity.self.PermissionMenuEntity;
import com.sgb.kjwl.model.entity.shopping.ShoppingCarResponse;
import com.sgb.kjwl.model.entity.user.ConcreteEntity;
import com.sgb.kjwl.model.entity.user.GoodsListEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.repository.HomeRepertory;
import com.sgb.kjwl.view.ui.activity.self.userInfo.SetPwdActivity;
import com.sgb.kjwl.view.ui.activity.supplier3.NewGoodsMapFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.ListResponse;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.entity.GoodsPublishEntity;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author Administrator
 */
public class GoodsMapFragmentModel extends BaseViewModel {
    private final NewGoodsMapFragment newGoodsMapFragment;
    private final HomeRepertory repertory;
    public List<PermissionMenuEntity> list = new ArrayList<>();

    public GoodsMapFragmentModel(NewGoodsMapFragment newGoodsMapFragment, HomeRepertory repertory) {
        this.newGoodsMapFragment = newGoodsMapFragment;
        this.repertory = repertory;
    }

    @SuppressLint("CheckResult")
    public void getDistanceModel() {
        repertory.getDistance()
                .subscribe(listBaseEntity -> {
                    if (listBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
                        newGoodsMapFragment.showDistancePopWindow(listBaseEntity.getData());
                    }
                }, throwable -> MLog.d(AppConstant.API_LOG, "error " + throwable.getMessage()));
    }

    /**
     * 获取全部商品
     *
     * @param map
     */
    public void getGoodsList(Map<String, Object> map) {
        DialogHelper.showProgressDialog2(newGoodsMapFragment.getContext(), null, "获取信息中...", 0, false, null, false);
        NewAPIManager.getInstance().getGoodsAPI().getGoodsList(map).enqueue(new Callback<BaseEntity<ListResponse<List<GoodsListEntity>>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<ListResponse<List<GoodsListEntity>>>> call, @NotNull Response<BaseEntity<ListResponse<List<GoodsListEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getData() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    newGoodsMapFragment.showGoodsList(response.body().getData().getList());
                    newGoodsMapFragment.addGoodsMarkInfoWindow(response.body().getData().getList());
                } else {
                    MToast.showToast(newGoodsMapFragment.getContext(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<ListResponse<List<GoodsListEntity>>>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getConcreteList(Map<String, Object> map) {
        DialogHelper.showProgressDialog2(newGoodsMapFragment.getActivity(), null, "加载中...", 0, false, null, false);
        NewAPIManager.getInstance().getGoodsAPI().getConcreteList(map).enqueue(new Callback<BaseEntity<ListResponse<List<ConcreteEntity>>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<ListResponse<List<ConcreteEntity>>>> call, @NotNull Response<BaseEntity<ListResponse<List<ConcreteEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getData() == null || response.body().getData().getList() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    List<GoodsListEntity> data = new ArrayList<>();
                    for (ConcreteEntity concreteEntity : response.body().getData().getList()) {
                        data.add(new GoodsListEntity(true, "", concreteEntity.getDistance(), concreteEntity.getSelfSupportTag(), concreteEntity.getProviderName(), concreteEntity.getTitle(), 0, "", concreteEntity.getImage(), concreteEntity.getUnit(), concreteEntity.getCompanyNo()
                                , concreteEntity.getPrice(), "", concreteEntity.getId(), concreteEntity.getProviderId(), "", "", "", "", concreteEntity.getSort(), false, concreteEntity.getRanking(), concreteEntity.getStorageName(), concreteEntity.getLon(), concreteEntity.getLat(), concreteEntity.getLowestBuy(), concreteEntity.getImAccount()));
                    }
                    newGoodsMapFragment.showGoodsList(data);
                    newGoodsMapFragment.addGoodsMarkInfoWindow(data);
                } else {
                    MToast.showToast(newGoodsMapFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<ListResponse<List<ConcreteEntity>>>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(newGoodsMapFragment.getActivity(), t.getMessage());
            }
        });
    }

    public void oneKeyLogin(OneKeyLoginEntity oneKeyLoginEntity, int type, GoodsListEntity entity) {
        if (newGoodsMapFragment.getActivity() != null && !newGoodsMapFragment.getActivity().isFinishing() && !newGoodsMapFragment.getActivity().isDestroyed()) {
            DialogHelper.showProgressDialog2(newGoodsMapFragment.getActivity(), null, "数据加载中...", 0, false, null, false);
        }
        APIManager.getInstance().getUserAPI().oneClickLogin(oneKeyLoginEntity).enqueue(new ICallBack<BaseEntity<LoginEntity>>(true, true) {
            @Override
            public void onSuccess(BaseEntity<LoginEntity> data) {
                if (data == null || data.getData() == null) {
                    return;
                }
                OneKeyLoginManager.getInstance().finishAuthActivity();
                if (data.getData().isNeedRegister()) {
                    Intent intent = new Intent(newGoodsMapFragment.getActivity(), SetPwdActivity.class);
                    intent.putExtra("mobile", data.getData().getPhone());
                    newGoodsMapFragment.getActivity().startActivityForResult(intent, 10);
                } else {
                    //登录成功逻辑
                    SharedPreferenceUtil.getInstance().cleatData();
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PC_TOKEN, data.getData().getResourcePCToken());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, data.getData().getToken());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, data.getData().getPhone());
                    JPushInterface.setAlias(newGoodsMapFragment.getActivity(), 1, data.getData().getPhone());
                    newGoodsMapFragment.oneKeyLoginSuccess(type, entity);
                }
            }
        });
    }

    /**
     * 获取商品ImAccount
     *
     * @param userNo
     */
    public void getGoodsImAccount(String userNo,int type) {
        if (newGoodsMapFragment.getActivity() != null && !newGoodsMapFragment.getActivity().isFinishing() && !newGoodsMapFragment.getActivity().isDestroyed()) {
            DialogHelper.showProgressDialog2(newGoodsMapFragment.getActivity(), null, "数据加载中...", 0, false, null, false);
        }
        NewAPIManager.getInstance().getCommonAPI().itemImAlternate(userNo, type).enqueue(new Callback<BaseEntity<EnquiryImAlternateEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<EnquiryImAlternateEntity>> call, Response<BaseEntity<EnquiryImAlternateEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (response.body().getData().getConfirmType() != null && 2 == response.body().getData().getConfirmType()) {
                        if (!TextUtils.isEmpty(response.body().getData().getConfirmMessage())) {
                            MToast.showToast(newGoodsMapFragment.getActivity(), response.body().getData().getConfirmMessage());
                        }
                    } else {
                        List<EnquiryImAlternateEntity.CompanyCustomersDTO> companyCustomers = response.body().getData().getCompanyCustomers();
                        if (companyCustomers != null) {
                            newGoodsMapFragment.showImWindow(companyCustomers);
                        }
                    }
                } else {
                    MToast.showToast(newGoodsMapFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<EnquiryImAlternateEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });

    }

    public void getGoodsItemInformationById(String id, String skuId, String shopId) {
        NewAPIManager.getInstance().getGoodsReleasedAPI().getNewGoodsById(id).enqueue(new ICallBack<BaseEntity<GoodsPublishEntity>>() {
            @Override
            public void onSuccess(BaseEntity<GoodsPublishEntity> data) {
                if (data == null || data.getData() == null) {
                    Toast.makeText(newGoodsMapFragment.getActivity(), "数据异常", Toast.LENGTH_SHORT).show();
                    return;
                }
                newGoodsMapFragment.setGoodsItemInformation(data.getData(), id, skuId, shopId);
            }
        });
    }

    public void getDetailModel(String pid, String skuId, String shopId, GoodsPublishEntity entity) {

        NewAPIManager.getInstance().getGoodsAPI().getSkuDetail(pid, skuId).enqueue(new ICallBack<BaseEntity<GoodsSkuDetailEntity>>() {
            @Override
            public void onSuccess(BaseEntity<GoodsSkuDetailEntity> data) {
                if (data == null || data.getData() == null) {
                    Toast.makeText(newGoodsMapFragment.getActivity(), "数据异常", Toast.LENGTH_SHORT).show();
                    return;
                }
                newGoodsMapFragment.buildGoodsItemParam(data.getData(), entity, shopId);
            }
        });
    }

    /***
     * 加入采购单
     * @param shoppingCarRequest
     */
    public void addShoppingCar(ShoppingCarRequest shoppingCarRequest, boolean isPurchase) {
        if (newGoodsMapFragment.getActivity() != null && !newGoodsMapFragment.getActivity().isFinishing() && !newGoodsMapFragment.getActivity().isDestroyed()) {
            DialogHelper.showProgressDialog2(newGoodsMapFragment.getActivity(), null, "数据加载中...", 0, false, null, false);
        }
        NewAPIManager.getInstance().getShoppingCarNewOrderAPI().addShoppingCar(shoppingCarRequest).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data != null) {
                    if (isPurchase) {
                        getShoppingCarInfo(shoppingCarRequest.getSkuId());
                    } else {
                        MToast.showToast(newGoodsMapFragment.getActivity(), data.getMsg());
                    }
                }
            }
        });
    }

    /***
     * 获取购物车列表数据
     * @param
     */
    private void getShoppingCarInfo(String skuId) {
        DialogHelper.showProgressDialog2(newGoodsMapFragment.getActivity(), null, "数据加载中...", 0, false, null, false);

        NewAPIManager.getInstance().getShoppingCarNewOrderAPI().getShoppingCarEntity().enqueue(new Callback<BaseEntity<List<ShoppingCarResponse>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<List<ShoppingCarResponse>>> call, @NotNull Response<BaseEntity<List<ShoppingCarResponse>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    newGoodsMapFragment.showShoppingCarDetail(response.body().getData(), skuId);
                } else {
                    MToast.showToast(newGoodsMapFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<List<ShoppingCarResponse>>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getWebsiteInfo(Map<String, String> map, String websiteNo, int type) {
        DialogHelper.showProgressDialog2(newGoodsMapFragment.getActivity(), null, "数据加载中...", 0, false, null, false);
        APIManager.getInstance().getWebsiteInfoAPI().getSiteInfo(map).enqueue(new ICallBack<BaseEntity<WebsiteInfoEntity>>() {
            @Override
            public void onSuccess(BaseEntity<WebsiteInfoEntity> data) {
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    if (data.getData() == null) {
                        MToast.showToast(newGoodsMapFragment.getActivity(), TextUtils.isEmpty(data.getMsg()) ? "当前未查询到网站详情" : data.getMsg());
                        return;
                    }
                    newGoodsMapFragment.showWebsiteInfo(data.getData(), websiteNo, type);
                }
            }

            @Override
            public void onFail() {
                super.onFail();
            }
        });
    }


    public void getPermissionMenu(WebsiteInfoEntity entity, int websiteType, String websiteNo, String companyName, int type) {
        String companyNo;
        if (websiteType == 0) {
            companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        } else {
            companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        }
        if (!TextUtils.isEmpty(companyNo)) {
            getBottomPermission(entity, websiteType, websiteNo, companyName, type);
        }
    }

    private void getBottomPermission(WebsiteInfoEntity entity, int websiteType, String websiteNo, String companyName, int type) {
        newGoodsMapFragment.getPermission(entity, websiteType, websiteNo, companyName, type);
    }

    /****
     * 获取供应商的详细信息
     * @param companyId
     */
    public void getCompanyInformation(GoodsSkuDetailEntity skuDetailEntity, GoodsPublishEntity goodsPublishEntity, String companyId) {
        DialogHelper.showProgressDialog2(newGoodsMapFragment.getActivity(), null, "数据加载中...", 0, false, null, false);
        NewAPIManager.getInstance().getMaterialAPI().getGoodsCompanyInfoDetailsFront(companyId).enqueue(new ICallBack<BaseEntity<CompanyDetailsEntity>>() {
            @Override
            public void onSuccess(BaseEntity<CompanyDetailsEntity> data) {
                if (data == null || data.getData() == null) {
                    Toast.makeText(newGoodsMapFragment.getActivity(), "数据异常", Toast.LENGTH_SHORT).show();
                    return;
                }
                newGoodsMapFragment.buildCheckParam(skuDetailEntity, goodsPublishEntity, data.getData());
            }
        });
    }

    public void getConcreteDetail(String id) {
        DialogHelper.showProgressDialog2(newGoodsMapFragment.getActivity(), null, "获取信息中...", 0, false, null, false);
        NewAPIManager.getInstance().getGoodsAPI().getConcreteDetail(id).enqueue(new ICallBack<BaseEntity<ConcreteDetailEntity>>() {
            @Override
            public void onSuccess(BaseEntity<ConcreteDetailEntity> data) {
                if (data == null || data.getData() == null) {
                    Toast.makeText(newGoodsMapFragment.getActivity(), "数据异常", Toast.LENGTH_SHORT).show();
                    return;
                }
                getCompanyInformation(data.getData());
            }
        });
    }

    private void getCompanyInformation(ConcreteDetailEntity concreteDetailEntity) {
        NewAPIManager.getInstance().getMaterialAPI().getGoodsCompanyInfoDetailsFront(concreteDetailEntity.getShopId()).enqueue(new Callback<BaseEntity<CompanyDetailsEntity>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<CompanyDetailsEntity>> call, @NotNull Response<BaseEntity<CompanyDetailsEntity>> response) {
                if (response.body() == null || response.body().getData() == null) {
                    Toast.makeText(newGoodsMapFragment.getActivity(), "数据异常", Toast.LENGTH_SHORT).show();
                    return;
                }
                newGoodsMapFragment.showConcreteCompanyDetail(response.body().getData(), concreteDetailEntity.getTitle());
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<CompanyDetailsEntity>> call, @NotNull Throwable t) {
            }
        });
    }
}
